<template>
    <el-form label-width="120px" ref="ruleFormRef" :model="formData" :rules="rules">
        <el-card shadow="never" class="!border-none">
            <div class="px-[10px]">
                <div class="font-extrabold text-lg">基本信息</div>
                <div class="mt-[20px]">
                    <el-form-item label="是否开启" prop="enable">
                        <div>
                            <el-radio-group v-model="formData.enable">
                                <el-radio label="0">关闭</el-radio>
                                <el-radio label="1">开启</el-radio>
                            </el-radio-group>
                            <div class="form-tips">
                                关闭或开启积分签到功能，关闭后商城的积分签到处于未开启状态
                            </div>
                        </div>
                    </el-form-item>
                </div>
            </div>
        </el-card>
        <el-card shadow="never" class="!border-none mt-4">
            <div class="px-[10px]">
                <div class="font-extrabold text-lg">签到规则</div>
                <div class="mt-[20px]">
                    <el-form-item label="每天签到奖励" prop="changeless">
                        <div class="flex">
                            <div class="flex-none">固定奖励</div>
                            <el-input class="w-[200px] ml-2" v-model.number="formData.changeless">
                                <template #append>
                                    <div>积分</div>
                                </template>
                            </el-input>
                        </div>
                    </el-form-item>
                    <el-form-item label="连续签到奖励">
                        <div>
                            <el-button type="primary" @click="addColumn">添加</el-button>
                            <el-table class="mt-4" :data="tableData">
                                <el-table-column label="连续天数" min-width="180">
                                    <template #default="{ row }">
                                        <el-input v-model="row.date"></el-input>
                                    </template>
                                </el-table-column>
                                <el-table-column label="连续奖励" min-width="180">
                                    <template #default="{ row }">
                                        <el-input v-model.number="row.award"></el-input>
                                    </template>
                                </el-table-column>
                                <el-table-column label="排序" min-width="180">
                                    <template #default="{ row }">
                                        <el-input
                                            @change="sortChange"
                                            v-model="row.sort"
                                        ></el-input>
                                    </template>
                                </el-table-column>
                                <el-table-column label="操作" min-width="120">
                                    <template #default="scoped">
                                        <el-button
                                            link
                                            type="primary"
                                            @click="delColumn(scoped.$index)"
                                            >删除</el-button
                                        >
                                    </template>
                                </el-table-column>
                            </el-table>
                        </div>
                    </el-form-item>
                    <el-form-item label="签到规则">
                        <div class="w-[660px]">
                            <Editor height="500px" v-model="formData.rule_description"></Editor>
                        </div>
                    </el-form-item>
                </div>
            </div>
        </el-card>
        <FooterBtns>
            <el-button
                type="primary"
                @click="submitForm(ruleFormRef)"
                v-perms="['ls:system:config:sign-in:edit']"
                >保存</el-button
            >
        </FooterBtns>
    </el-form>
</template>
<script setup lang="ts">
import { signInEdit, signInDetail } from '@/api/finance/finance'
import feedback from '@/utils/feedback'
import { objectSort } from '@/utils/util'
import type { FormInstance, FormRules } from 'element-plus'

//interface
interface ItableData {
    date: string
    award: string
    sort: string
}
interface IformData {
    enable: number | string
    changeless: number | string
    reward_rules_json: string
    rule_description: string
}
// interface end

//表单ref
const ruleFormRef = ref<FormInstance>()
//表格数据
const tableData = ref<ItableData[]>([])
//表单数据
const formData = ref<IformData>({
    enable: '0',
    changeless: '',
    reward_rules_json: '',
    rule_description: ''
})

//表单校验规则
const rules = reactive<FormRules>({
    enable: [{ required: true, message: '请选择是否开启', trigger: 'blur' }],
    changeless: [{ required: true, message: '请输入签到奖励', trigger: 'blur' }]
})

//添加行数
const addColumn = () => {
    tableData.value.push({ date: '', award: '', sort: '0' })
}
//删除行
const delColumn = (row: any) => {
    // console.log(tableData.value)
    tableData.value.splice(row, 1)
}

//获取配置详情
const getDetail = async () => {
    formData.value = await signInDetail()
    tableData.value = JSON.parse(formData.value.reward_rules_json)
}

//排序改变
const sortChange = () => {
    objectSort(tableData.value, 'sort')
}

//连续签到规则校验
const rulesValidate = () => {
    return new Promise((resolve, reject) => {
        const dateList = tableData.value.map((item) => item.date)
        tableData.value.map((item: any, index: any) => {
            Object.keys({ date: '', award: '', sort: '' }).map((item1) => {
                if (item[item1] == '' || Number(item[item1]) < 0) {
                    feedback.msgError('连续签到奖励规则不能为空或不能为负数！')
                    reject('err')
                    throw ''
                }
            })

            let count = 0
            dateList.forEach((item2) => {
                if (item2 == item.date) count++
                if (count == 2) {
                    feedback.msgError('连续签到奖励规则连续天数不能相同')
                    reject('err')
                    throw ''
                }
            })
        })
        resolve(true)
    })
}

//提交
const submitForm = async (formEl: FormInstance | undefined) => {
    if (!formEl) return
    await formEl.validate(async (valid, fields) => {
        if (valid) {
            try {
                await rulesValidate()
                formData.value.reward_rules_json = JSON.stringify(tableData.value)
                await signInEdit(formData.value)
                feedback.msgSuccess('修改成功！')
                await getDetail()
            } catch (error) {
                console.log(error)
            }
        } else {
            console.log('error submit!', fields)
        }
    })
}

onMounted(() => {
    getDetail()
})
</script>
<style lang="scss" scoped></style>
